package com.breeze.toolkit.retrofit;

import com.breeze.toolkit.ui.LoadingController;
import com.breeze.toolkit.ui.UIUpdateListener;
import com.breeze.toolkit.util.ConstantsUtil;

import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * Created by john on 2016/8/23.
 */
public class RetrofitCallback<T extends APIBaseResponse> implements Callback<T> {
	private APIRequestCallback<T> mCallback;//请求结果接口，用于UI层数据处理或UI控制
	private LoadingController mLoadingController;//加载框控制器，用以请求结束时是否关闭加载框，展示失败提示信息
	private UIUpdateListener mUIUpdateListener;//UI更新接口，用以请求失败或无数据返回时UI展示

	public RetrofitCallback(APIRequestCallback<T> callback) {
		mCallback = callback;
	}

	public void setLoadingController(LoadingController controller) {
		mLoadingController = controller;
	}

	public void setUIUpdateListener(UIUpdateListener listener) {
		mUIUpdateListener = listener;
	}

	/**
	 * 接口应答回调
	 * @param response 接口应答相关数据
	 * @param retrofit 请求配置
	 */
	@Override
	public void onResponse(Response<T> response, Retrofit retrofit) {
		try {
			T rsp = response.body();

			if (rsp != null) {
				stopLoading(rsp.getMessage(), !rsp.isSuccess());

				if (mUIUpdateListener != null && rsp.isSuccess() && rsp.isEmpty()) {
					mUIUpdateListener.showEmptyContentView();
				}

				if (mCallback != null) {
					if (rsp.isSuccess()) {
						mCallback.onServerBusinessSuccess(rsp, retrofit);
					} else {
						mCallback.onServerBusinessFailed(rsp, retrofit);
					}
				}
			} else {
				processExceptionResponse(retrofit);
			}
		} catch (Exception e) {
			processExceptionResponse(retrofit);
			e.printStackTrace();
		}
	}

	/**
	 * 连接服务器失败时处理
	 * @param t 连接失败异常信息
	 */
	@Override
	public void onFailure(Throwable t) {
		t.printStackTrace();
		stopLoading(ConstantsUtil.NO_NETWORK_NOTICE, true);

		noResponse();

		if (mCallback != null) {
			mCallback.onServerFailure(t);
		}
	}

	/**
	 * 数据异常时处理
	 * @param retrofit 初始请求配置
	 */
	private void processExceptionResponse(Retrofit retrofit) {
		if (mCallback != null) {
			mCallback.onServerBusinessFailed(null, retrofit);
		}

		stopLoading(ConstantsUtil.NO_NETWORK_NOTICE, true);

		noResponse();
	}

	/**
	 * 关闭加载框, 需要时toast提示失败信息
	 * @param msg 失败信息
	 * @param isShowToast true 展示, false 不展示
	 */
	private void stopLoading(String msg, boolean isShowToast) {
		if (mLoadingController != null) {
			mLoadingController.setToastMsg(msg);
			if (isShowToast) {
				mLoadingController.stop();
			} else {
				mLoadingController.close();
			}
		}
	}

	private void noResponse() {
		if (mUIUpdateListener != null) {
			mUIUpdateListener.showConnectExceptionView(true);
		}
	}
}
